package com.strongbj.iot.devices.newlight.response.handle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.core.util.ContextUtils;
import com.strongbj.iot.devices.newlight.entity.TagInfo;
import com.strongbj.iot.devices.newlight.message.NewLightMQMessage;
import com.strongbj.iot.devices.newlight.message.NewLightOSMessageFactory;
import com.strongbj.iot.devices.newlight.message.NewLightReaderMessage;
import com.strongbj.iot.mq.producer.TopicSender;

import cn.hutool.core.date.DateUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

public class TagInfoHandle implements IMessageHandle<NewLightReaderMessage, Object> {
	private static Logger logger = LogManager.getLogger(TagInfoHandle.class);
	private static final byte TAG_INFO_COMMAND = Integer.valueOf("4C", 16).byteValue();
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	private NewLightOSMessageFactory newLightOSMessageFactory = (NewLightOSMessageFactory) ContextUtils
			.getBean("newLightOSMessageFactory");

	@Override
	public boolean isHandle(NewLightReaderMessage t) {
		return TAG_INFO_COMMAND == t.getType();
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, NewLightReaderMessage t) {
		String hostNumber = ByteUtil.bytesToAddress(t.getAddress()); // reader 地址码
		try {
			short tagCount = ByteUtil.byteArrToShort(t.getBody(), 2); // 当前标签个数
			List<TagInfo> tags = new ArrayList<>();
			for (int i = 0; i < tagCount; i++) {
				TagInfo tag = new TagInfo();
				tag.setTag(ByteUtil.bytesToIp(t.getBody(), i * 10 + 4));
				tag.setTemperature(ByteUtil.byteArrToShort(t.getBody(), i * 10 + 8));
				tag.setHumidity(ByteUtil.byteArrToShort(t.getBody(), i * 10 + 10));
				tags.add(tag);
			}

			NewLightMQMessage mes = new NewLightMQMessage();
			mes.setActioncode("tagInfo");
			mes.setGUID(String.valueOf(DateUtil.date().getTime()));
			Map<String, Object> result = new HashMap<>();
			result.put("readerCode", hostNumber);
			result.put("tagInfos", tags);
			mes.setPostdata(result);
			logger.info("=========tagInfos=======" + JSON.toJSONString(mes));
			topicSender.send("wh.reader." + hostNumber + ".message", JSON.toJSONString(mes));
			sendTagInfoResponse(ctx.channel(), t.getAddress(), true, t.getTime());
		} catch (Exception e) {
			logger.error("", e);
			sendTagInfoResponse(ctx.channel(), t.getAddress(), false, t.getTime());
		}
		return null;
	}

	@Override
	public void destory() {

	}

	private void sendTagInfoResponse(Channel channel, byte[] deviceCode, boolean isSuccess, byte[] timestamp) {
		byte[] datas = new byte[1];
		datas[0] = isSuccess ? (byte) 0x01 : (byte) 0x00;
		byte[] req = newLightOSMessageFactory.createNewLightOSMessage(deviceCode, TAG_INFO_COMMAND, datas, timestamp);
		ByteBuf bs = Unpooled.copiedBuffer(req);
		ChannelFuture cf = channel.writeAndFlush(bs);
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("发送标签反馈命令成功 设备编号:{} 发送命令:{}", deviceCode,ByteUtil.byteArrToHexString(req));
				} else {
					logger.debug("发送标签反馈命令失败 设备编号:{} 发送命令:{}", deviceCode,ByteUtil.byteArrToHexString(req));
				}
			}

		});
	}
}
